package cn.micai.base.concurrent;

/**
 * 描述：银行账户类
 * <p>
 *     线程干扰
 *
 * @author: 赵新国
 * @date: 2018/5/11 17:42
 */
public class BankAccount {

    private int number;
    private int balance;

    public BankAccount(int number, int balance) {
        this.number = number;
        this.balance = balance;
    }

    public int getBalance() {
        return balance;
    }

    /**
     * 存款
     * @param amount
     */
    public void deposit(int amount) {
        synchronized (this) {
            balance = balance + amount;
        }
    }

    /**
     * 取款
     * @param amount
     */
    public void withdraw(int amount) {
        synchronized (this) {
            balance = balance - amount;
        }
    }

    public static void main(String [] args) {
        try {
            BankAccount account = new BankAccount(1, 1000);
            Thread thread1 = new Thread(new Depositor(account, 100), "deposit");
            Thread thread2 = new Thread(new Withdrawer(account, 100), "withdraw");
            thread1.start();
            thread2.start();
            thread1.join();
            thread2.join();
            System.out.println(account.getBalance());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 存款人
     */
    static class Depositor implements Runnable {
        BankAccount account;
        int amount;
        public Depositor(BankAccount account, int amount) {
            this.account = account;
            this.amount = amount;
        }
        @Override
        public void run() {
            for (int i=0; i<100000; i++) {
                account.deposit(amount);
            }
        }
    }

    /**
     * 取款人
     */
    static class Withdrawer implements Runnable {
        BankAccount account;
        int amount;
        public Withdrawer(BankAccount account, int amount) {
            this.account = account;
            this.amount = amount;
        }
        @Override
        public void run() {
            for (int i=0; i<100000; i++) {
                account.withdraw(amount);
            }
        }
    }


}
